<?php
namespace app\controller;

use app\BaseController;
use app\controller\model;
use liliuwei\think\Auth;
use think\facade\Session;
use think\facade\Db;
class Gas extends BaseController
{
	protected $getpath="";
	protected $gobaluser="";
	protected $tables;
	public function __construct(){
		checkuser();
		$this->gobaluser=Session::get("uid");
		$this->tables=new model\Tables();
	}

	public function getGasList(){
		//手动拉取渠道油站数据
		$supplierID = request()->param("supplierID");
		$supplier = DB::name($this->tables->supplier)->where("id",$supplierID)->find();
		if(!$supplier)echojson([],1,'ID错误');
		$model = new model\Supplier($supplierID);
		$model->getGasList($supplier['upNum']+1);//同步油站
	}
	public function gunAdd(){
		$id = request()->param("id");
		$prices = DB::name($this->tables->gasPrice)->where("gasID",$id)->select()->toArray();
		foreach ($prices as &$v){
			$v['gun_nos']=json_decode($v['gun_nos'],true);
		}
		return view("gunAdd")->assign(['oil'=>$prices]);
	}
	public function gunSave(){
		$id = request()->param("id");
		$data = request()->param("data");
		$re = DB::name($this->tables->gas)->where("id",$id)->find();
		if(!$re)echojson([],1,'ID错误');
		$data = json_decode($data,true);
		if(is_array($data) && count($data)>0){
			foreach ($data as $v){
				$price = DB::name($this->tables->gasPrice)->where("gasID",$id)->where("oil_no",$v[0])->find();
				if(!$price)echojson([],1,$v[0]."记录错误");
				$gunsArr=[];
				foreach ($v as $k2=>$v2){
					if($k2==0)continue;
					$gunsArr[]=['gun_no'=>$v2];
				}
				if(count($gunsArr)>0){
					DB::name($this->tables->gasPrice)->where("id",$price['id'])->update(['gun_nos'=>json_encode($gunsArr)]);
				}
			}
		}
		echojson();
	}



	public function gas(){
		$classesModel = new \app\controller\model\Classes();
		return view("gas")->assign(['fromID'=>$classesModel->rSupplierToOption()[0],'tips'=>$classesModel->rTipsToOption()[0]]);
	}
	public function tips(){
		$classesModel = new \app\controller\model\Classes();
		return view("tips");
	}
	public function tipsAdd(){
		$id = request()->param("id");
		$id<1?$id=0:'';
		if($id>0){
			$re = DB::name($this->tables->tips)->where("id",$id)->find();
		}else{
			$re=[];
		}
		return view("tipsAdd")->assign(['data'=>$re]);
	}
	public function tipsSaveIDS(){
		$type = request()->param("type");
		$tipsID = request()->param("tipsID");
		$tip = DB::name($this->tables->tips)->where("id",$tipsID)->find();
		if($tip['ids']=='' || $tip['ids']==null){
			$tipsGasIDS = [];
		}else{
			$tipsGasIDS = explode(",",$tip['ids']);
		}
		if(!$tip)echojson([],1,'标签ID错误');
		$checkIds = json_decode(request()->param("checkIds"),true);
		$gases = DB::name($this->tables->gas)->whereIn("id",$checkIds)->select();
		foreach ($gases as $v){
			if($v['tipsID']=='' || $v['tipsID']==null){
				$tips=[];
			}else{
				$tips = explode(",",$v['tipsID']);
			}
			$up = false;
			if($type=='add'){
				if(!in_array($tipsID,$tips)){
					$up=true;
					$tips[]=$tipsID;
					$tipsGasIDS[]=$v['id'];
				}
			}
			if($type=='del'){
				$key = array_search($tipsID, $tips);
				if ($key !== false) {
					$up=true;
					$key2 = array_search($v['id'], $tipsGasIDS);
					if ($key2 !== false) {
						unset($tipsGasIDS[$key2]);
					}
					unset($tips[$key]);
				}
			}
			if($up == true){
				DB::name($this->tables->tips)->where("id",$tipsID)->update(['ids'=>implode(",",$tipsGasIDS)]);
				DB::name($this->tables->gas)->where("id",$v['id'])->update(['tipsID'=>implode(",",$tips)]);
			}
		}
		echojson();
	}
	public function tipsList(){
		$cid = request()->param("cid");
		$cid>0?$where="cid=$cid":$where='1=1';
		$status = request()->param("status");
		$status==-1?$where.=" and status=-1":$where.=' and status=1';
		$title = request()->param("title");
		$title!=''?$where.=" and title like '%$title%'":'';
		$res = getpagedata($this->tables->tips,"",true,$where);
		$count = $res[1];
		$res = $res[0];
		$res = $res->all();
		foreach ($res as $k=>$v){
			$res[$k]['cid']=$v['cid']==1?"油站标签":"服务商标签";
		}
		pagejson($res,0,'',$count);
	}
	public function tipsSave(){
		$id = request()->param("id");
		$status = request()->param("status");
		$data = request()->param();
		unset($data['id']);
		if($status==1 || $status==-1){
			if(DB::name($this->tables->tips)->where("id",$id)->update(['status'=>$status]))echojson();
			echojson([],1,'更新失败');
		}
		if($id>0){
			$re = DB::name($this->tables->tips)->where("id",$id)->find();
			if(!$re)echojson([],1,"ID错误");
		}
		if($id>0){
			$re = r_one($this->tables->tips,"id=$id");
			if($re){
				DB::name($this->tables->tips)->where("id",$id)->update($data);
				echojson([],0,'更新成功');
			}else{
				echojson([],1,'ID错误');
			}
		}else{
			$data['addTime']=nowTime();
			$re = DB::name($this->tables->tips)->insert($data);
			if($re){
				echojson([],0,'添加成功');
			}else{
				echojson([],1,'更新错误');
			}
		}
	}

	public function task(){
		$classesModel = new \app\controller\model\Classes();
		return view("task")->assign(['tips'=>$classesModel->rTipsToOption()[0]]);
	}
	public function taskList(){
		$ctype = request()->param("ctype");
		$ctype>0?$where="ctype=$ctype":$where='1=1';
		$status = request()->param("status");
		$status==-1?$where.=" and status=-1":$where.=' and status>=0';
		$tips = request()->param("tips");
		$tips!=''?$where.=" and tipsID = $tips":'';
		$res = getpagedata($this->tables->taskGas,"",true,$where);
		$count = $res[1];
		$res = $res[0];
		$res = $res->all();
		foreach ($res as $k=>$v){
			$res[$k]['ctypeStr']=$v['ctype']==1?"让利比例":"每周价格";
		}
		pagejson($res,0,'',$count);
	}

	public function taskAdd(){
		$classesModel = new \app\controller\model\Classes();
		$id = request()->param("id");
		$id<1?$id=0:'';
		$taskModel = new model\Task();
		if($id>0){
			$re = DB::name($this->tables->taskGas)->where("id",$id)->find();
			if(!$re)echojson([],1,'ID错误');
			$re['rule'] = $taskModel->getTaskPrice($re);
			$re['tipsIDS']="[".$re['tipsIDS']."]";
		}else{
			$re=[];
			$re['rule'] = $taskModel->getTaskPrice();
			$re['tipsIDS']="[]";
		}
		$tips = $classesModel->rTipsToOption((isset($re['tipsID'])?$re['tipsID']:0));
		return view("taskAdd")->assign(['data'=>$re,'tipsAllIDS'=>json_encode($tips[3])]);
	}
	public function taskSave(){
		$data = request()->param();
		unset($data['id']);
		$id = request()->param("id");
		$tipsIDS = request()->param("tipsIDS");
		$ctype = request()->param('ctype');
		foreach ($data as $v){
			if($v=='')echojson([],1,'所有必填');
		}
		if($ctype==2){
			foreach ($data['rule'] as $v){
				foreach ($v as $v2){
					if($v2<=0)echojson([],1,'金额不可为0');
				}
			}
		}
		if($tipsIDS!=''){
			$tipsIDS = json_decode($tipsIDS,true);
			$temArr=[];
			foreach ($tipsIDS as $v){
				$temArr[] = $v['value'];
			}
			$data['tipsIDS'] = implode(",",$temArr);
		}
		if($id>0){
			$re = r_one($this->tables->taskGas,"id=$id");
			if($re){
				if($ctype==2)$data['rule'] = json_encode($data['rule']);
				DB::name($this->tables->taskGas)->where("id",$id)->update($data);
				echojson([],0,'更新成功');
			}else{
				echojson([],1,'ID错误');
			}
		}else{
			$data['addTime']=nowTime();
			if($ctype==2)$data['rule'] = json_encode($data['rule']);

			$re = DB::name($this->tables->taskGas)->insert($data);
			if($re){
				echojson([],0,'添加成功');
			}else{
				echojson([],1,'ID错误');
			}
		}
	}
	public function gasPush(){
		$id = request()->param("id");
		$gas = DB::name($this->tables->gas)->where("id",$id)->inc("upNumber")->update();
		if(!$gas)echojson([],1,'ID错误');
		echojson();
	}
	public function getGas(){
		$id = request()->param("id");
		$gas = DB::name($this->tables->gas)->where("id",$id)->find();
		if(!$gas)echojson([],1,'ID错误');
		$model = new model\Supplier($gas['fromID']);
		if($model->getGas($gas))echojson([],0,'更新成功');
		echojson([],1,'更新成功');
	}

	 public function updateGasGun()
    {
       $guns = DB::name($this->tables->gasPrice)->where('gun_nos is null OR gun_nos = "[]"')->group("gasID")->column("gasID");
        // dd($guns);
        foreach ($guns as $v){
            $gas = DB::name($this->tables->gas)->where("id",$v)->find();
            $model = new model\Supplier($gas['fromID']);
            $model->getGas($gas);
        }
        return json($guns);
    }
	public function gasEdit(){
		$id = request()->param("id");
		$id<1?$id=0:'';
		if($id>0){
			$re = DB::name($this->tables->gas)->where("id",$id)->find();
		}else{
			return "信息错误";
		}
		if(!$re)echojson([],1,'ID错误');
		$gasModel = new model\Gas($id);
		$re['prices'] = $gasModel->getGasPrice();
		return view("price")->assign(['data'=>$re]);
	}
	public function gasLocalSave(){
		$id = request()->param("id");
		$clear = request()->param("clear");
		if($clear=="true"){
			if(DB::name($this->tables->gasPrice)->where("gasID",$id)->update(['tail'=>null]))echojson();
			echojson([],1,'状态未改变');
		}
		if($id>0){
			$re = DB::name($this->tables->gas)->where("id",$id)->find();
		}else{
			return "信息错误";
		}
		if(!$re)echojson([],1,'ID错误');
		$gasModel = new model\Gas($id);
		$gasModel->SaveGasPrice(request()->param("data"));
	}
	public function listAdd(){
		$id = request()->param("id");
		$id<1?$id=0:'';
		if($id>0){
			$re = DB::name($this->tables->gas)->where("id",$id)->find();
			if($re){
				$temOil=[];
				$temOilPrice=[];
				$prices = DB::name($this->tables->gasPrice)->where("gasID",$id)->select();
				foreach ($prices as $v){
					if($v['oil_no']=='92#'){
						$temOil[]="92#";
						$temOilPrice['a92']=$v;
					}
					if($v['oil_no']=='95#'){
						$temOil[]="95#";
						$temOilPrice['a95']=$v;
					}
					if($v['oil_no']=='98#'){
						$temOil[]="98#";
						$temOilPrice['a98']=$v;
					}
					if($v['oil_no']=='0#'){
						$temOil[]="0#";
						$temOilPrice['a0']=$v;
					}
				}
				$re['prices'] = $temOil ;
				$re['pricesArr'] = $temOilPrice ;
			}else{
				$re['prices'] = [];
				$re['pricesArr'] = [];
			}
		}else{
			$re = ['fromID'=>0];
		}
		$classesModel = new model\Classes();
		return view("add")->assign(['data'=>$re,'fromID'=>$classesModel->rSupplierToOption($re['fromID'])[0]]);
	}
	public function gasList($inTips=''){
		$cid = request()->param("cid");
		$cid>0?$where="cid=$cid":$where='1=1';
		$status = request()->param("status");
		$fromID = request()->param("fromID");
		$tips = request()->param("tips");
		$date1 = request()->param("date1");
		$date2 = request()->param("date2");
		$date3 = request()->param("date3");
		$date4 = request()->param("date4");
		if($date1!='' && $date2!=''){
			$where .= " and addTime>='$date1 00:00:00' and addTime<='$date2 23:59:59'";
		}
		if($date3!='' && $date4!=''){
			$where .= " and taskTime>='$date3 00:00:00' and taskTime<='$date4 23:59:59'";
		}
		$status==-1?$where.=" and status=-1":$where.=' and status=1';
		$cid = request()->param("cid");
		$cid>0?$where.=" and cid=$cid":'';
		$fromID>0?$where.=" and fromID=$fromID":'';
		if($tips>0){
			$where .= " and id in (".rTipsToIds($tips).")";
		}
		$name = request()->param("name");
		$name!=''?$where.=" and name like '%$name%'":'';
		$inTips!=''?$where.=" and tipsID in ($inTips)":'';

		$title = request()->param("title");
		$title!=''?$where.=" and name like '%$title%'":'';

		$res = getpagedata($this->tables->gas,"",true,$where);
		$count = $res[1];
		$res = $res[0];
		$supplier = DB::name($this->tables->supplier)->field("id,title")->select();
		$res = $res->all();
		$classesModel = new model\Classes();
		foreach ($res as $k=>$v){
			$res[$k]['fromID']=rclasstitle($supplier,$v['fromID']);
			$res[$k]['tipsID']=rIdsToTips($v['tipsID']);
		}
		pagejson($res,0,'',$count);
	}
	public function gasSave(){
		$data = request()->param();
		unset($data['id']);
		unset($data['oil_no']);
		$id = request()->param("id");
		$field = request()->param('field');
		$oil_no = request()->param("oil_no");
//		$prices = request()->param("prices");
		if($oil_no!='')$oil_no=json_decode($oil_no,true);
//		if($prices!='')$prices=json_decode($prices,true);

		if($field=='subPrice'){
			$subPrice = request()->param('value');
			$re = DB::name($this->tables->gas)->where("id",$id)->find();
			!$re?echojson([],1,'ID错误'):'';
			$up =  DB::name($this->tables->gas)->where("id",$id)->update(['subPrice'=>$subPrice]);
			if(!$up)echojson([],1,'更新失败');
			echojson();
		}
		foreach ($data as $v){
			if($v=='')echojson([],1,'所有必填');
		}
//
		if($id>0){
			$re = r_one($this->tables->gas,"id=$id");
			if($re){
				DB::name($this->tables->gas)->where("id",$id)->update($data);
				$this->setGasNo($id,$oil_no);
				DB::name($this->tables->gas)->where("id",$id)->inc("upNumber")->update();
				echojson([],0,'更新成功');
			}else{
				echojson([],1,'ID错误');
			}
		}else{
			$data['addTime']=nowTime();
			$re = DB::name($this->tables->gas)->insertGetId($data);
			if($re){
				$this->setGasNo($re,$oil_no);
				DB::name($this->tables->gas)->where("id",$re)->inc("upNumber")->update();
				echojson([],0,'添加成功');
			}else{
				echojson([],1,'ID错误');
			}
		}
	}
	protected function setGasNo($gasID=0,$oil_no=[]){
		DB::name($this->tables->gasPrice)->where("gasID",$gasID)->update(['status'=>0]);
		foreach ($oil_no as $k=>$v){
			$re = DB::name($this->tables->gasPrice)->where("gasID",$gasID)->where("oil_no",$v['oil_no'])->find();
			$v['status']=1;
			$v['gasID']=$gasID;
			if($re){
				DB::name($this->tables->gasPrice)->where("id",$re['id'])->update($v);
			}else{
				DB::name($this->tables->gasPrice)->insert($v);
			}
		}
	}

}
